package ead.cs.service;

import com.google.gson.Gson;
import ead.cs.domain.alert.Message;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AlertConsumer {

    private static final Logger LOGGER = Logger.getLogger(AlertConsumer.class);

    @Autowired
    private EmailSender emailSender;
    @Autowired
    private SmsSender smsSender;

    public void receiveMessage(String rabbitMessage) {
        LOGGER.info("Rabbit message received --> " + rabbitMessage);
        final Message message = convert(rabbitMessage);
        LOGGER.info("Message Type --> " + message.getType());
        if (Message.MessageType.EMAIL.equals(message.getType())) {
            LOGGER.info("Message type is email. Try to send email");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    emailSender.sendMail(message.getRecipient(), "Notification from MSC", message.getContent());
                }
            }).start();

        }
        if (Message.MessageType.SMS.equals(message.getType())) {
            LOGGER.info("Message type is sms. Try to send sms");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    smsSender.sendSms(message.getRecipient(), message.getContent());
                }
            }).start();

        }
    }

    private Message convert(String message) {
        return new Gson().fromJson(message, Message.class);
    }

}
